package com.ie.intelligence_education.interceptor;

import com.alibaba.fastjson.JSON;
import com.ie.intelligence_education.utils.BaseContext;
import com.ie.intelligence_education.utils.Result;
import com.ie.intelligence_education.utils.BaseContext;
import com.ie.intelligence_education.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    //路径匹配器，支持模糊匹配的写法的匹配
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("(拦截器)拦截到请求：{}",request.getRequestURI());
        //获取本次请求的URI
        String requestURI = request.getRequestURI();
        //定义不需要处理的请求
        String[] trueUrls = new String[]{
                "/teacher/login",
                "/teacher/logout",
                "/backend/**",
                "/front/**",
                "common/**",
                "/user/sendMsg",
                "/user/login",
                "/error"
        };
        //判断本次请求是否需要处理
        boolean check = check(trueUrls,requestURI);
        //不需要处理则直接放行
        if (check){
            log.info("本次请求不需要处理：{}",request.getRequestURI());
            return true;
        }
        //判断是否登录
        if (request.getSession().getAttribute("teacher") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("teacher"));
            long id = Thread.currentThread().getId();
            log.info("线程id为：{}",id);
            Long empId = (Long) request.getSession().getAttribute("teacher");
            BaseContext.setCurrentId(empId);
            return true;
        }

        if (request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            //将用户的id存入线程中，供线程后面的地方调用
            long id = Thread.currentThread().getId();
            log.info("线程id为：{}",id);
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            return true;
        }

        log.info("用户未登录");
        //如果未登录，通过输出流的方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(Result.build(null,ResultCodeEnum.NOTLOGIN)));
        return false;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     */
    public boolean check(String[] trueUrls,String requestURI){
        for (String trueUrl : trueUrls) {
            boolean match = PATH_MATCHER.match(trueUrl, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
